package com.token.iot.bratterycharging.gateway.business;

import java.util.Date;
import java.util.HashMap;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;

import com.google.gson.Gson;
import com.outstanding.framework.base.SpringContextHolder;
import com.outstanding.framework.base.mq.MQProducer;
import com.outstanding.framework.core.Logger;
import com.outstanding.framework.core.PendingException;
import com.outstanding.framework.core.TransactionContext;
import com.outstanding.framework.log.LoggerFactory;
import com.token.iot.bratterycharging.gateway.AbstractOper;
import com.token.iot.bratterycharging.gateway.IDGeneration;
import com.token.iot.bratterycharging.gateway.IMEI;
import com.token.iot.bratterycharging.gateway.Oper;
import com.token.iot.bratterycharging.gateway.SemaphoreManager;
import com.token.iot.bratterycharging.gateway.api.Constant;
import com.token.iot.bratterycharging.gateway.api.FeeFinish;
import com.token.iot.bratterycharging.gateway.api.LocalFee;
import com.token.iot.bratterycharging.gateway.api.StopReason;

import io.netty.channel.ChannelHandlerContext;

/**
 * 充电状态响应
 * 
 * @author chenzhixuan
 *
 */
@Component("UWCOper")
public class UWCOper extends AbstractOper {

	private static Logger loger = LoggerFactory.getLogger("transactionLogger");

	@Autowired
	private MQProducer mQProducer;

	@Override
	public int onCall(byte[] b, ChannelHandlerContext ctx) throws PendingException {
		String val = new String(b);
		loger.info(" the UWC response =" + val);
		String imei = IMEI.getIMEI(ctx);
		String sessionid = IDGeneration.getSessionID(b);
		String left = val.substring(14);

		String[] params = left.split("#/#");

		FeeFinish ff = new FeeFinish();
		ff.setImei(imei);
		try {
			int amount = Integer.parseInt(params[1]);
			ff.setLeftTime(amount);
			int port = Integer.parseInt(params[0]);
			ff.setPort(port);
			int  refund= Integer.parseInt(params[4]);
			ff.setRefund(refund);
		} catch (Exception e) {
			loger.error(e);
		}
		StopReason sr = StopReason.getByCode(params[2]);
		ff.setStopReason(sr);
		ff.setCard(params[3]);
		Gson gs = new Gson();
		String str = gs.toJson(ff);
		mQProducer.sendMessageByQueue(Constant.MESSAGEHEAD + Constant.QueuefinishCharge, str);
		int lastPost = val.lastIndexOf("#/#");
		String no = val.substring(lastPost + 3);
		HashMap<String, String> map = new HashMap();
		map.put("NO", no);
		TransactionContext.putData(Constant.PARAMS, map);
		TransactionContext.putData(Constant.SENDER, "DLB");
		return 1;
	}

}
